import json
from django.forms import model_to_dict
from django.shortcuts import redirect, render
from django.http import HttpResponse, JsonResponse
from django.urls import reverse
from .models import ECS
from .client import aliyunEcsAdmin
# Create your views here.


def select_k8s_node(request):
    ecss = [ model_to_dict(ecs) for ecs in ECS.objects.all() ]
    ecsFields = [field.name for field in ECS._meta.get_fields()]
    ecsValues = [ [ ecs.get(field) for field in ecsFields] for ecs in ecss]
    context = {
       "ecss": ecss,
       "ecsFields": ecsFields,
       "ecsValues": ecsValues,
    }
    return render(request, "aliyun/select_k8s_node.html", context)

def delete_k8s_node(request, instanceId):
    if request.method == 'GET': 
        print(instanceId)
        ecs = ECS.objects.get(instanceId=instanceId)
        aliyunEcsAdmin.delete([instanceId])
        ecs.delete()
        return redirect(reverse('select')) 



def create_k8s_node(request):
    if request.method == 'GET': 
        ecss = [ model_to_dict(ecs) for ecs in ECS.objects.all() ]
        for ecs in ecss:
            ecs['delete'] = {
                'instanceId': ecs['instanceId']
            }
        ecsFields = [field.name for field in ECS._meta.get_fields()]
        # ecsFields.pop(ecsFields.index('delete'))
        ecsFields.append('delete')
        ecsValues = [ [ ecs.get(field) for field in ecsFields] for ecs in ecss]
        context = {
        "ecss": ecss,
        "ecsFields": ecsFields,
        "ecsValues": ecsValues,
        }
        return render(request, "aliyun/create_k8s_node.html", context)
    if request.method == 'POST':
        hostnames = json.loads(request.body)  
        
        instanceIds = aliyunEcsAdmin.create(hostnames)

        items = [{'instanceId': instanceId, 'hostname': hostname } for hostname, instanceId in zip(hostnames, instanceIds)]

        instances = aliyunEcsAdmin.select(instanceIds)

        # for instance in instances:
        #     
        #     print('公网地址')
        #     print(instance.public_ip_address.ip_address[0])
        #     print('私网地址')
        #     print(instance.vpc_attributes.private_ip_address.ip_address[0])
        #     print(instance.host_name)
        #     ecs = ECS(
        #         instanceId=instance.instance_id, 
        #         host=instance.public_ip_address.ip_address[0], 
        #         hostname=instance.host_name
        #     )
        #     ecs.save()

        for item in items:
            ecs = ECS(**item)
            ecs.save()

        return JsonResponse({'status': 'success', 'message': '数据已接收', 'instanceIds': instanceIds}) 

